import { Toast } from "react-vant";
const infodata = {
  data: [],
  childrenData: [],
  code: 0,
  userarr: {},
  shopcardata:[]
};

const reducer = (state = infodata, { type, payload }: any) => {
  let newState = JSON.parse(JSON.stringify(state));
  const show_Toast = (code: number, message: string) => {
    switch (code) {
      case 200:
        return Toast.success(payload.message);
      case 500:
        return Toast.fail(payload.message);
      default:
        break;
    }
  };
  switch (type) {
    case "GET_LIST":
      newState.data = payload;
      newState.childrenData = payload[0].children;
      return newState;
    case "CHECK_ACTIVE":
      newState.childrenData = newState.data[payload].children;
      return newState;
    case "LOGIN_MY":
      if (payload.code === 200) {
        newState.userarr = {
          username: payload.username,
          password: payload.password,
        };
        window.localStorage.setItem(
          "token",
          JSON.stringify({
            username: payload.username,
            password: payload.password,
          })
        );
      }
      show_Toast(payload.code, payload.message);
      newState.code = payload.code;
      return newState;
      case "ADD_SHOPCAR":
        newState.childrenData.forEach((item:any, index:number) => {
            if (item.id === payload) {
              //  console.log(item.id);
                newState.shopcardata.push(item)
            }
        })
        
        return newState
        case "ADD_NUM":
          newState.shopcardata.forEach((item:any, index:number) => {
              if (item.id === payload) {
                //  console.log(item);
                  item.num++
                 // console.log(newState.shopcardata.num);
              }
          })
          
          return newState

          case "SUB_NUM":
            newState.shopcardata.forEach((item:any, index:number) => {
                if (item.id === payload) {
                   if(item.num>0){
                   item.num--
                   }else{
                    alert("最少只能是0")
                   }
                }
            })
            return newState

       
    default:
      return newState;
  }
};
export default reducer;
